class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < n - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < n - 1; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                int target = -nums[i] - nums[j];
                int l = j + 1, r = n - 1;
                while (l <= r) {
                    int mid = (l + r) >> 1;
                    if (nums[mid] > target) {
                        r = mid - 1;
                    } else if (nums[mid] < target) {
                        l = mid + 1;
                    } else {
                        ans.add(Arrays.asList(nums[i], nums[j], target));
                        break;
                    }
                }
            }
        }
        return ans;
    }
}